package com.itheima.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.itheima.excption.BusinessException;
import com.itheima.excption.MyException;
import com.itheima.vo.ErrorResult;
import com.itheima.pojo.UmsAdmin;
import com.itheima.pojo.UmsMenu;
import com.itheima.pojo.UmsRole;
import com.itheima.util.JWTUtil;
import com.itheima.vo.PageResultVo;
import com.itheima.vo.Result;
import com.itheima.vo.UmsInfoVo;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UmsAdminService {
    @DubboReference
    private UmsAdminApi umsAdminApi;
    @DubboReference
    private UmsAdminRoleRelationApi roleRelationApi;
    @DubboReference
    private UmsRoleApi roleApi;
    @DubboReference
    private UmsRoleMenuRelationApi menuRelationApi;
    @DubboReference
    private UmsMenuApi menuApi;

    public Result login(UmsAdmin umsAdmin) {
        String username = umsAdmin.getUsername();
//查询用户是否存在
        if (StringUtil.isNullOrEmpty(username)) return Result.error(null, "用户名不存在");
        UmsAdmin admin = umsAdminApi.login(username);
        if (ObjectUtil.isEmpty(admin)) throw new MyException("用户不存在");
//检验密码D
        String hex = DigestUtil.md5Hex(umsAdmin.getPassword());
        if (!StringUtils.equals(hex, admin.getPassword())) throw new MyException("密码错误jj");
        if (admin.getStatus()==0)throw new MyException("账户封禁中错误");
//登录成功,封装token,修改用户状态
        admin.setLoginTime(LocalDateTime.now());
        umsAdminApi.updateAdmin(admin);
        Map map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        log.info(admin.getId()+"");
       // Map gettoken = new HashMap();
       // gettoken.put("token", map);
       // gettoken.put("tokenHead", "Bearer ");
        String token = JWTUtil.getToken(map);
        Map map1 = new HashMap<>();
        map1.put("token", token);
        return Result.success(map1);
    }

    //获取当前登录用户的信息
    public Result findById(Long userId) {
        if (userId == null) throw new MyException("查无此人");
        UmsAdmin admin = umsAdminApi.findById(userId);
        UmsInfoVo vo = new UmsInfoVo();
        vo.setIcon(admin.getIcon());
        vo.setUsername(admin.getUsername());
        List<Long> adminRoleIds = roleRelationApi.getAdminRoleId(admin.getId());
        if (CollUtil.isEmpty(adminRoleIds)) throw new MyException("该用户尚未分配角色");
        List<UmsRole> roles = roleApi.getByIds(adminRoleIds);
        StringBuilder name = new StringBuilder("");
        List<Long> roleIds = new ArrayList<>();
        for (UmsRole role : roles) {
            roleIds.add(role.getId());
            name.append(role.getName());
        }
        vo.setRoles(name.toString());
        List<Long> menuIds = menuRelationApi.getRoleMenuIds(roleIds);
        List<UmsMenu> menus = menuApi.findByIds(menuIds);
        vo.setMenus(menus);
        return Result.success(vo);
    }

    //根据id删除用户
    public void deleteById(Long userId) {
        if (userId == 3) throw new MyException("不能删除超级管理员");
        boolean flag = umsAdminApi.deleteById(userId);
        if (!flag) throw new MyException("不能删除正在使用的用户账号");
        roleRelationApi.deleteByAdminId(userId);
    }

    //分页查询用户信息
    public PageResultVo list(String keyword, Integer pageNum, Integer pafeSize) {
        PageResultVo resultVo = umsAdminApi.list(keyword, pageNum, pafeSize);
        if (ObjectUtil.isEmpty(resultVo)) return new PageResultVo();
        return resultVo;
    }

    //用户注册
    public void register(UmsAdmin admin) {
        boolean flag = umsAdminApi.register(admin);
        if (!flag) throw new MyException("注册失败,账号重复");
    }


    //给用户分配角色
    public void updateRole(Integer adminId, List<Integer> roleIds) {
        UmsAdmin admin = umsAdminApi.findById(Long.valueOf(adminId));
        if (ObjectUtil.isEmpty(admin)) throw new MyException("该用户不存在");
        if (ObjectUtil.isEmpty(roleIds)) roleRelationApi.save(adminId, roleIds);
        else roleRelationApi.update(adminId,roleIds);
        getCount();
    }

    //给角色确定有多少个用户
    public void getCount() {
        List<UmsAdmin> admins = umsAdminApi.selectAll();
        List<Long> ids = CollUtil.getFieldValues(admins, "id", Long.class);
        String counts = "";
        for (Long id : ids) {
            List<Long> roleIds = roleRelationApi.getAdminRoleId(id);
            counts = counts + roleIds.toString();
        }
        String[] split = counts.split("");
        List<UmsRole> roles = roleApi.selectAll();
        List<Long> roleIds = CollUtil.getFieldValues(roles, "id", Long.class);
        for (Long roleId : roleIds) {
            int count = 0;
            for (String s : split) {
                if (StringUtils.equals(roleId.toString(), s)) count++;
            }
            roleApi.setCount(roleId, count);
        }
    }

    public List<UmsRole> getRoles(Long adminId) {
        if (adminId == 3) throw new MyException("该用户无对应操作权限");
        List<Long> roleIds = roleRelationApi.getAdminRoleId(adminId);
        if (CollUtil.isEmpty(roleIds)) throw new MyException("该用户无角色");
        List<UmsRole> roles = roleApi.getByIds(roleIds);
        return roles;
    }

    public void updateAdmin(UmsAdmin admin) {

        umsAdminApi.updateAdmin(admin);
    }

    //修改密码
    public void updatePassword(String newPassword, String oldPassword, String username) {
        if (StringUtils.isEmpty(newPassword)) throw new MyException("新密码不能为空");
        if (StringUtils.isEmpty(oldPassword)) throw new MyException("旧密码不能为空");
        if (StringUtils.isEmpty(username)) throw new MyException("用户名不能为空");
        String password = DigestUtil.md5Hex(newPassword);
        UmsAdmin admin = new UmsAdmin();
        admin.setPassword(password);
        umsAdminApi.updatePassword(admin);
    }

    public void updateStatus(Long id, Integer status) {
        umsAdminApi.updateStatus(id, status);
    }

    public UmsAdmin find(Long id) {
        if (id == null) throw new MyException("查询id不能为空");
        return umsAdminApi.findById(id);
    }
}
